package com.example.mqmanager.controller;

import com.example.mqmanager.dto.QueueInfo;
import com.example.mqmanager.service.RabbitMQMonitorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/rabbitmq")
@CrossOrigin(origins = "*")
public class RabbitMQMonitorController {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMQMonitorController.class);

    @Autowired
    private RabbitMQMonitorService rabbitMQMonitorService;

    /**
     * 更新RabbitMQ配置
     */
    @PostMapping("/config")
    public ResponseEntity<String> updateRabbitMQConfig(
            @RequestParam String host,
            @RequestParam int port,
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String virtualHost) {
        try {
            rabbitMQMonitorService.updateRabbitMQConfig(host, port, username, password, virtualHost);
            return ResponseEntity.ok("配置更新成功");
        } catch (Exception e) {
            logger.error("更新RabbitMQ配置时出错", e);
            return ResponseEntity.badRequest().body("配置更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有队列信息
     * 
     * @return 队列列表
     */
    @GetMapping("/queues")
    public ResponseEntity<List<QueueInfo>> getAllQueues() {
        // 当前实现返回空列表，实际项目中应通过RabbitMQ Management API获取
        List<QueueInfo> queues = new ArrayList<>();
        return ResponseEntity.ok(queues);
    }

    /**
     * 获取指定队列的消息数量
     * 
     * @param queueName 队列名称
     * @param virtualHost Virtual Host（可选）
     * @return 消息数量
     */
    @GetMapping("/queues/{queueName}/messages")
    public ResponseEntity<?> getMessageCount(
            @PathVariable String queueName,
            @RequestParam(required = false) String virtualHost) {
        try {
            long messageCount;
            if (virtualHost != null && !virtualHost.isEmpty()) {
                messageCount = rabbitMQMonitorService.getMessageCount(queueName, virtualHost);
            } else {
                messageCount = rabbitMQMonitorService.getMessageCount(queueName);
            }
            return ResponseEntity.ok(messageCount);
        } catch (Exception e) {
            logger.error("获取队列消息数量时出错: " + queueName, e);
            return ResponseEntity.badRequest()
                .body("获取队列消息数量时出错: " + e.getMessage());
        }
    }

    /**
     * 获取指定队列的详细信息
     * 
     * @param queueName 队列名称
     * @param virtualHost Virtual Host（可选）
     * @return 队列信息
     */
    @GetMapping("/queues/{queueName}")
    public ResponseEntity<?> getQueueInfo(
            @PathVariable String queueName,
            @RequestParam(required = false) String virtualHost) {
        try {
            QueueInfo queueInfo;
            if (virtualHost != null && !virtualHost.isEmpty()) {
                queueInfo = rabbitMQMonitorService.getQueueInfo(queueName, virtualHost);
            } else {
                queueInfo = rabbitMQMonitorService.getQueueInfo(queueName);
            }
            return ResponseEntity.ok(queueInfo);
        } catch (Exception e) {
            logger.error("获取队列信息时出错: " + queueName, e);
            return ResponseEntity.badRequest()
                .body("获取队列信息时出错: " + e.getMessage());
        }
    }

    /**
     * 获取队列中的消息内容
     * 
     * @param queueName 队列名称
     * @param count 获取消息数量
     * @param virtualHost Virtual Host（可选）
     * @return 消息列表
     */
    @GetMapping("/queues/{queueName}/contents")
    public ResponseEntity<?> getQueueMessages(
            @PathVariable String queueName,
            @RequestParam(defaultValue = "10") int count,
            @RequestParam(required = false) String virtualHost) {
        try {
            List<String> messages;
            if (virtualHost != null && !virtualHost.isEmpty()) {
                messages = rabbitMQMonitorService.getMessages(queueName, count, virtualHost);
            } else {
                messages = rabbitMQMonitorService.getMessages(queueName, count);
            }
            return ResponseEntity.ok(messages);
        } catch (IOException e) {
            logger.error("获取队列消息时出错: " + queueName, e);
            return ResponseEntity.badRequest()
                .body("获取队列消息时出错: " + e.getMessage());
        }
    }
    
    /**
     * 删除队列中的消息
     * 
     * @param queueName 队列名称
     * @param count 删除消息数量
     * @param virtualHost Virtual Host（可选）
     * @return 删除结果
     */
    @DeleteMapping("/queues/{queueName}/messages")
    public ResponseEntity<?> removeMessages(
            @PathVariable String queueName,
            @RequestParam(defaultValue = "1") int count,
            @RequestParam(required = false) String virtualHost) {
        try {
            // 如果没有指定virtualHost，使用默认的
            String vhost = (virtualHost != null && !virtualHost.isEmpty()) ? virtualHost : "/";
            int removedCount = rabbitMQMonitorService.removeMessages(queueName, count, vhost);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("removedCount", removedCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除队列消息时出错: " + queueName, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "删除队列消息时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 删除队列中的单条消息
     * 
     * @param queueName 队列名称
     * @param virtualHost Virtual Host（可选）
     * @return 删除结果
     */
    @DeleteMapping("/queues/{queueName}/message")
    public ResponseEntity<?> removeSingleMessage(
            @PathVariable String queueName,
            @RequestParam(required = false) String virtualHost) {
        try {
            // 如果没有指定virtualHost，使用默认的
            String vhost = (virtualHost != null && !virtualHost.isEmpty()) ? virtualHost : "/";
            boolean removed = rabbitMQMonitorService.removeSingleMessage(queueName, vhost);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", removed);
            if (removed) {
                result.put("message", "消息删除成功");
            } else {
                result.put("message", "没有消息可删除");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("删除队列消息时出错: " + queueName, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", "删除队列消息时出错: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}